package org.fnzn.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.fnzn.bean.FnglGrade;
import org.fnzn.bean.FnglMyGrade;
import org.fnzn.bean.FnglStaff;
import org.fnzn.bean.LrdUserrole;
import org.fnzn.bean.vo.User;
import org.fnzn.core.Constants;
import org.fnzn.core.Page;
import org.fnzn.core.Result;
import org.fnzn.dao.FnglGradeMapper;
import org.fnzn.service.FnglGradeService;
import org.fnzn.service.FnglStaffService;
import org.fnzn.service.base.AbstractService;
import org.fnzn.util.CommonUtil;
import org.fnzn.util.DateTools;
import org.fnzn.util.ResultGenerator;
import org.fnzn.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class FnglGradeServiceImpl extends AbstractService<FnglGrade> implements FnglGradeService {

    @Autowired(required = false)
    private FnglGradeMapper FnglGradeMapper;
    @Autowired
    private FnglGradeService fnglGradeService;
    @Autowired
    private UserRoleServiceImpl userRoleServiceImpl;
    @Autowired
    private FnglStaffService fnglStaffService;

    @Override
    public Result findFnglGrade(FnglGrade FnglGrade, Page page) {
        if (page.getLimit() != null && page.getPage() != 0) {
            // 获取到当前登录用户所属角色
            User user = CommonUtil.getUser();
            LrdUserrole userrole = userRoleServiceImpl.findBy("userId", user.getUser_id());
            String roleId = userrole.getRoleId();
            String projectId = user.getProjectId();
            List<FnglGrade> newList = new ArrayList<>();
            // 如果是超级管理员和财务人员登录，那么能看到所有销售人员的绩效信息
            if(roleId.equals(Constants.FINANCIAL_ROLE)||roleId.equals(Constants.ADMIN_ROLE)){
                 newList = FnglGradeMapper.getAllGrade();
            }
            // 如果当前是销售经理登录，那么只能看到自己项目下所有销售人员绩效信息
            if (roleId.equals(Constants.MANAGER_ROLE)) {
                // 根据销售人员id分组获取到
                 newList = FnglGradeMapper.getTotalGrade(projectId);
            }
            // 如果当前是销售人员登录，那么只能看到自己的绩效信息
            if (roleId.equals(Constants.SALESMAN_ROLE)) {
                String staffId = fnglStaffService.getStaffId(user.getUser_id());
                newList = FnglGradeMapper.getOwnGrade(staffId);
            }
            PageHelper.startPage(page.getPage(), page.getLimit(), true);
            page.setRows(newList);
            page.setTotal(new PageInfo(newList).getTotal());
            return ResultGenerator.genSuccessResult(page);
        }
        return ResultGenerator.genFailResult("查询失败");
    }


    @Override
    public Result updateFnglGrade(FnglGrade fnglGrade) {
        fnglGrade.setUpdateTime(new Date());
        // 改变已发放佣金和未发放佣金
        // 已发佣金
        double paid = Double.valueOf(fnglGrade.getPaid());
        // 总佣金
        double payment = Double.valueOf(fnglGrade.getPayment());
        // 设置未发佣金
        fnglGrade.setUnpaid((payment - paid) + "");
        int n = update(fnglGrade);
        if (n > 0) {
            return ResultGenerator.genSuccessResult(fnglGrade);
        } else {
            return ResultGenerator.genFailResult("更新失败");
        }
    }

    /**
     * 根据销售人员获取到绩效详情
     *
     * @return
     */
    @Override
    public Result getGradeDetail(FnglGrade fnglGrade, Page page) {

        if (page.getLimit() != null && page.getPage() != 0) {

            if (StringUtil.isEmpty(fnglGrade.getStaffId())) {
                return ResultGenerator.genFailResult("获取数据失败");
            }
            Condition condition = new Condition(FnglGrade.class);
            Example.Criteria criteria = condition.createCriteria();
            // 根据删除状态查询
            criteria.andEqualTo("delFlag", 0);
            // 根据销售人员id查询
            criteria.andEqualTo("staffId", fnglGrade.getStaffId());
            if (StringUtil.isEmpty(fnglGrade.getStaffName())) {
                criteria.andEqualTo("staffName", fnglGrade.getStaffName());
            }
            condition.setOrderByClause("create_time desc");
            PageHelper.startPage(page.getPage(), page.getLimit(), true);
            List<FnglGrade> fnglGrades = findByCondition(condition);
            page.setRows(fnglGrades);
            page.setTotal(new PageInfo(fnglGrades).getTotal());

            return ResultGenerator.genSuccessResult(fnglGrades);
        }
        return ResultGenerator.genFailResult("查询失败");
    }

    /**
     * 获取到我的绩效
     */
    @Override
    public Result getMyGrade(String phone) {
        if (StringUtil.isEmpty(phone)) {
            return ResultGenerator.genFailResult("获取数据失败");
        }
        String staffId = fnglStaffService.getStaffId(phone);
        Condition condition = new Condition(FnglGrade.class);
        Example.Criteria criteria = condition.createCriteria();
        // 根据删除状态查询
        criteria.andEqualTo("delFlag", 0);
        // 根据销售人员id获取到绩效
        criteria.andEqualTo("staffId", staffId);
        condition.setOrderByClause("create_time desc");
        List<FnglGrade> list = findByCondition(condition);
        FnglMyGrade fnglMyGrade = new FnglMyGrade();
        if (list != null && list.size() > 0) {
            // 定义总绩效，已结算，未结算
            double Sumpayment = 0.0;
            double Sumpaid = 0.0;
            double Sumunpaid = 0.0;
            for (FnglGrade item : list) {
                Sumpayment += Double.valueOf(item.getPayment());
                Sumpaid += Double.valueOf(item.getPaid());
                Sumunpaid += Double.valueOf(item.getUnpaid());
            }

            fnglMyGrade.setPayment(String.valueOf(Sumpayment));
            fnglMyGrade.setPaid(String.valueOf(Sumpaid));
            fnglMyGrade.setUnpaid(String.valueOf(Sumunpaid));
        }
        // 获取到当月的绩效
        // 获取到当前时间
        String endTime = DateTools.getCurrentSysData(DateTools.DEFAULT_FORMAT);
        // 获取到当前年份
        int year = DateTools.getCurrentYear();
        // 获取到当前月份
        int month = DateTools.getCurrentMonth();
        // 拼接成当前月份第一天
        String startTime = year + "-" + month + "-" + 01;
          List<FnglGrade> gradeList = FnglGradeMapper.getMyGrade(staffId, startTime, endTime);
          if (gradeList != null && gradeList.size() > 0) {
            // 定义当月绩效
            double currentMonthPayment = 0.0;
            for (FnglGrade item : gradeList) {
                currentMonthPayment += Double.valueOf(item.getPayment());
            }
            fnglMyGrade.setCurrentMonthGrade(currentMonthPayment);
            return ResultGenerator.genSuccessResult(fnglMyGrade);
        }
        return ResultGenerator.genFailResult("获取数据失败");
    }
}
